﻿// --------------------------------------------------------------------------------------------------------------------- 
// <copyright file="SerializerInstance.cs" company="Scrum for Team System">
//   None
// </copyright>
// <summary>
// Defines the SerializerInstance type.
// </summary>
// ---------------------------------------------------------------------------------------------------------------------
namespace ScrumForTeamSystem.EventService.Infrastructure
{
    using System.Globalization;
    using System.IO;
    using System.Text;
    using System.Xml.Serialization;

    using Interfaces;

    /// <summary>
    /// Defines the SerializerInstance&lt;T&gt; type.
    /// </summary>
    /// <typeparam name="T">
    /// The type to serialise
    /// </typeparam>
    public class SerializerInstance<T> : ISerializer<T> where T : class, new()
    {
        /// <summary>
        /// Serializer instance.
        /// </summary>
        private XmlSerializer serializer;

        /// <summary>
        /// Gets Serializer.
        /// </summary>
        /// <value>
        /// The serializer.
        /// </value>
        private XmlSerializer Serializer
        {
            get
            {
                return this.serializer = this.serializer ?? new XmlSerializer(typeof(T));
            }
        }

        /// <summary>
        /// Deserializes the specified source XML.
        /// </summary>
        /// <param name="sourceXml">
        /// The source xml.
        /// </param>
        /// <returns>
        /// The desrialised object
        /// </returns>
        public T Deserialize(string sourceXml)
        {
            T newObject;
            StringReader tr = null;

            try
            {
                tr = new StringReader(sourceXml);
                newObject = (T)this.Serializer.Deserialize(tr);
            }
            finally
            {
                if (tr != null)
                {
                    tr.Close();
                }
            }

            return newObject;
        }

        /// <summary>
        /// Serializes the specified source object.
        /// </summary>
        /// <param name="sourceObject">
        /// The source object.
        /// </param>
        /// <returns>
        /// A serialised representation of the source object.
        /// </returns>
        public string Serialize(T sourceObject)
        {
            var sb = new StringBuilder();
            StringWriter sw = null;

            try
            {
                sw = new StringWriter(sb, CultureInfo.InvariantCulture);
                this.Serializer.Serialize(sw, sourceObject);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
            }

            return sb.ToString();
        }
    }
}